import React from 'react';
import {View, Image} from 'react-native';
import { Lt, Color, Label, Dialog, Jpp, Jx, Images, Navigator, Input, Button, Oview, Nav, Storage, cSys } from "./_utils";
import { Net, NET_NR, NET_NT, NET_RI } from "./_net"
import { Overlay } from "./_teaset"
import { toMainWithToken, toTaobao } from './PageAutoLogin';
import { ViewVerify } from './ViewVerify';

// 微信绑定手机/手机绑定微信
function promoseBind(wcData, pToken){
    return new Promise((resolve, reject)=>{
        Net.request("bindWx", {
            wx:wcData.unionid, 
            nickname:wcData.nickname, 
            headimgurl:wcData.headimgurl,
            token:pToken,
        }, {NET_NR, NET_NT}).then(r=>{
            if(r.data){
                resolve(r.data);
            }else{
                reject(r);
            }
        }).catch(err=>{
            reject(err);
        })
    });
}

// 弹出微信绑定
function OviewBind(cb){
    return Overlay.show(<Oview.Pad model={false} style = {{alignItems:"center", width:"40%"}}>
        <Image style={{marginVertical : 30}} source = {Images.weixin_d}/>
        <Label style={{fontSize:Lt.c16, color:Color.c6}}>绑定微信后才可正常使用</Label>
        <Button.FlexPure title = {"绑定微信"} onPress={cb || null} />
    </Oview.Pad>);
}

const c_placeholders = ["手机号", "验证码"];
// 手机登录界面
export class PageLogin extends React.PureComponent {
    constructor(props){
        super(props);
        const {wcData, account} = this.props.navigation.state.params;
        this.wcData = wcData;
        this.inputs = [account || "", ""];
        this.onClick = this.onClick.bind(this);
        
    }
    static navigationOptions = {
        headerTitle : null,
        headerStyle: {
            borderBottomWidth:0,
            elevation:0,
        },
    }

    // 手机绑定微信
    bindWchatWithUser(pToken){
        if(!cSys.isWechatInstalled(true)){
            return;
        }
        // 获取微信授权信息
        cSys.fetWchatRelease().then(wcData=>{
            // 授权信息与手机绑定
            promoseBind(wcData, pToken).then(token=>{
                Dialog.release();
                Overlay.hide(this.this.overlay);
                console.warn(Jx.stringify(token));
                // 是否绑定淘宝授权
                // 隐藏 overlay 来不及 Msg ? 算了, 让它弹点两次吧
                if(toTaobao(token)){
                    return;
                }
                // 绑定成功, 登录成功
                toMainWithToken(token, this.inputs[0])
            }).catch(err=>{
                Dialog.release();
            })
        }).catch(err=>{
            Dialog.release();
        })
    }

    onClick(){
        for(let k = 0 ; k < this.inputs.length; ++k){
            let str = Jx.checkInterger(this.inputs[k]);
            if(str){
                Dialog.msg1(c_placeholders[k] + str);
                return;
            }
        }
        // 手机与验证码登录
        Net.request("loginUser", {phone:this.inputs[0], validate:this.inputs[1]}, {NET_RI, NET_NT}).then(uData=>{
            console.warn(Jx.stringify(uData));
            // 是否绑定淘宝
            if(toTaobao(uData)){
                Dialog.release();
                return;
            }
            // 登录成功
            if(toMainWithToken(uData.data, this.inputs[0])){
                Dialog.release();
                return;
            }
            const pToken = uData.data.phone_token || "";
            if(!pToken){
                Dialog.release();
                return;
            }
            // 微信未绑定手机
            if(this.wcData){
                promoseBind(this.wcData, pToken).then(token=>{
                    Dialog.release();
                    console.warn(Jx.stringify(token));
                     // 是否绑定淘宝
                    if(toTaobao(token)){
                        return;
                    }
                     // 绑定成功, 登录成功
                    toMainWithToken(token, this.inputs[0]);
                }).catch(err=>{
                    Dialog.release();
                })
            }else{
            // 手机未绑定微信
                Dialog.release();
                // 弹出微信绑定
                this.overlay = OviewBind(()=>this.bindWchatWithUser(pToken));
            }
        }).catch(err=>{

        });
    }
    render(){
        let marh = 25;
        let title = this.wcData ? "绑定手机" : "手机快捷登录"; //["绑定手机", "手机快捷登录"][this.idx_bind_phone];
        let strBtn = this.wcData ? "绑定" : "登录"; // ["绑定", "登录"][this.idx_bind_phone];
        return <View style = {{flex:1}}>
            <Nav.StatusBar theme = {false}/>
            <Label style = {{fontSize:Lt.c20, margin:marh}}>{title}</Label>
            <Input.NumberLine style = {{
                marginHorizontal:marh,
                marginVertical:Lt.margin,
            }}
                placeholder={"输入" + c_placeholders[0]} 
                defaultValue = {this.inputs[0]}
                onChangeText = {t=>this.inputs[0]=t}
            />
            <View style = {{
                flexDirection:"row",
                justifyContent:"space-between",
                marginHorizontal:marh,
                marginVertical:Lt.margin,
                borderColor:Color.line,
                borderBottomWidth:1,
            }}
            >
                <Input.Number style = {{
                    flex:1,
                }}
                    placeholder={"输入" + c_placeholders[1]}
                    defaultValue = {this.inputs[1]}
                    onChangeText = {t=>this.inputs[1]=t}
                />
                <ViewVerify style = {{alignSelf:"center"}} onPhone={()=>this.inputs[0]}/>
            </View>

            <Button.FlexPure  title = {strBtn} onPress = {this.onClick}/>
        </View>
    }
}